<script setup lang="ts">
import { usegetUserMenu } from '@fl/api/iam-api'
import { useAddMenu, useGetMenuDetail } from '@fl/api/iam-api/menu'
import { SearchForm, SubmitBtn } from '@fl/components'
// import SvgIcon from '@fl/components/svgIcon.vue'
import { cloneDeep } from 'lodash-es'

import useForm from '../hooks/use-form'
import IconSelect from './icon-select.vue'

const props = withDefaults(
    defineProps<{
        parentId: number
        // menuId: any;
        treeData: []
    }>(),
    {
        treeData: () => [],
    },
)
const { parentId, treeData } = toRefs(props)
const initialForm = ref({
    icon: undefined,
    isCache: '0',
    isFrame: '1',
    menuId: undefined,
    menuName: undefined,
    menuType: 'M',
    orderNum: undefined,
    parentId: 0,
    status: '0',
    visible: '0',
})
const form: Ref<typeof initialForm.value> = ref(cloneDeep(initialForm.value))
const visible = defineModel('visible')
const menuId = defineModel('menuId')
watch(menuId, (val: any) => {
    form.value.menuId = val
}, {
    deep: true,
    immediate: true,
})

const formRef = ref()
const { isPending: isSubmitLoading, mutate: addMenuMutate } = useAddMenu()
const { refetch: refetchUserMenu } = usegetUserMenu(false)
const { data } = useGetMenuDetail(menuId)
const columns = useForm(form).formColumns
const iconSelectRef = ref<any>()
const rules = useForm(form).rules
function showSelectIcon() {
    iconSelectRef.value?.reset()
}
function selected(val) {
    form.value.icon = val
}
watchEffect(() => {
    if (!visible.value) {
        form.value = cloneDeep(initialForm.value)
    }
    if (parentId.value && !menuId.value) {
        form.value.parentId = parentId.value
    }
    if (data.value) {
        form.value = cloneDeep(data.value)
    }
})

// 处理树
function getTreeData(items, parentIdKey = 'parentId', idKey = 'menuId') {
    const tree = []
    const childrenOf = {}
    items.forEach((item) => {
        item.label = item.menuName
        item.value = item.menuId
        const parentId = item[parentIdKey]
        if (parentId === 0) {
            tree.push(item)
        }
        else {
            if (!childrenOf[parentId]) {
                childrenOf[parentId] = []
            }
            childrenOf[parentId].push(item)
        }
    })
    function findChildren(items) {
        return items.map((item) => {
            const foundChildren = childrenOf[item[idKey]] || []
            item.children = findChildren(foundChildren)
            item.length = item.children.length
            return item
        })
    }
    return findChildren(tree)
}
function addRoot(tree) {
    return [
        {
            children: tree,
            label: '主类目',
            value: 0,
        },
    ]
}
async function onSubmitBtnClick() {
    const valid = await formRef.value.formInstance.formInstance.validate()
    if (!valid)
        return
    addMenuMutate(form.value, {
        onSuccess: () => {
            ElMessage({
                message: '操作成功',
                type: 'success',
            })
            refetchUserMenu()
            cancel()
        },
    })
}
function cancel() {
    formRef.value.formInstance.formInstance.resetFields()
    visible.value = false
    form.value = cloneDeep(initialForm.value)
    menuId.value = null
}
</script>

<template>
    <SearchForm ref="formRef"
                v-model="form"
                :columns="columns"
                :rules="rules"
                :has-footer="false"
    >
        <template #plus-field-parentId>
            <el-tree-select v-model="form.parentId"
                            value="menuId"
                            label="menuName"
                            :data="addRoot(getTreeData(treeData))"
                            filterable
                            :check-strictly="true"
                            :default-expanded-keys="[0]"
                            node-key="value"
            >
                <template #default="{ data }">
                    {{ data.label
                    }}<span style="color: gray">{{
                        data.children.length !== 0 ? `(${data.children.length})` : ""
                    }}</span>
                </template>
            </el-tree-select>
        </template>

        <template #plus-field-icon>
            <el-popover placement="bottom-start"
                        :width="560"
                        trigger="click"
            >
                <template #reference>
                    <el-input v-model="form.icon"
                              placeholder="点击选择图标"
                              readonly
                              @blur="showSelectIcon"
                    >
                        <!-- <template #prefix>
                            <SvgIcon v-if="form.icon"
                                     :icon-class="form.icon"
                                     class="el-input__icon"
                                     style="height: 32px; width: 16px"
                            />

                            <el-icon v-else
                                     style="height: 32px; width: 16px"
                            >
                                <search />
                            </el-icon>
                        </template> -->
                    </el-input>
                </template>

                <IconSelect ref="iconSelectRef"
                            :active-icon="form.icon"
                            @selected="selected"
                />
            </el-popover>
        </template>
    </SearchForm>

    <div class="mt-16 flex justify-end">
        <SubmitBtn type="primary"
                   :loading="isSubmitLoading"
                   @click="onSubmitBtnClick"
        >
            提交
        </SubmitBtn>

        <el-button @click="cancel">
            取消
        </el-button>
    </div>
</template>

<style scoped lang="scss">
.icon-body {
    width: 100%;
    padding: 10px;
    .icon-list {
        height: 200px;
        overflow-y: scroll;
        div {
            height: 40px;
            line-height: 40px;
            font-size: 16px;
            margin: 5px 0 -5px 10px;
            cursor: pointer;
            width: 30%;
            float: left;
        }
        span {
            display: inline-block;
            vertical-align: -0.15em;
            fill: currentColor;
            overflow: hidden;
        }
    }
}
</style>
